<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <!-- 插入到left插槽位置 -->
        <template #left>
          <span>总条数:{{ total }}</span>
        </template>
        <!-- 插入到right插槽位置 -->
        <template #right>
          <el-button type="danger" size="small" @click="$router.push('/import')">导入excel</el-button>
          <el-button type="warning" size="small" @click="exportEmployee">导出excel</el-button>
          <el-button type="primary" size="small" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>
      <el-card style="margin-top: 10px">
        <el-table
          v-loading="loading"
          border
          :data="list"
          :default-sort="{ prop: 'workNumber' }"
        >
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="头像" width="110">
            <template #default="{row}">
              <!-- <img :src="scope.row.staffPhoto" alt="" width="80"> -->
              <el-image :src="row.staffPhoto" class="avatar" @click="createQr(row.staffPhoto)">
                <!-- 具名插槽新语法  图片加载出错的时候自动显示 -->
                <template #error>
                  <!-- <i class="el-icon-picture-outline" /> -->
                  <img src="@/assets/bigUserHeader.png" width="80">
                </template>
              </el-image>
            </template>
          </el-table-column>
          <el-table-column label="聘用形式">
            <template #default="scope">
              <!-- 插值表达式支持函数执行 并且渲染的是函数的return值 -->
              {{ formatEmployment(scope.row.formOfEmployment) }}
            </template>
          </el-table-column>

          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间">
            <template #default="{ row }">
              {{ formatDate(row.timeOfEntry) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail?yyds=`+row.id)">查看</el-button>
              <el-button type="text" size="small" @click="editRole(row.id)">分配角色</el-button>
              <el-button
                type="text"
                size="small"
                @click="hDelEmployee(row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <div style="height: 60px; margin-top: 10px">
          <el-pagination :total="total" layout="prev, pager, next" @current-change="handleCurrentChange" />
        </div>
      </el-card>
      <AddEmployee :show-dialog="showDialog" @close-dialog="closeDialog" />
    </div>
    <!-- 分享展示, 预览的二维码的弹层 -->
    <el-dialog title="二维码" :visible="showCodeDialog" @close="showCodeDialog = false">
      <!-- 二维码 -->
      <el-row type="flex" justify="center">
        <canvas ref="myCanvas" />
      </el-row>
    </el-dialog>
    <AssignRole ref="formRole" :cur-id="curId" :show-role-dialog="showRoleDialog" @assign-dialog="assignDialog" />
  </div>
</template>
<script>
import { reqGetEmployeeList, delEmployee } from '@/api/employees'
import AddEmployee from './components/add-employee'
import dayjs from 'dayjs'
import { getExportData } from '@/utils/excelData'
import QrCode from 'qrcode'
import AssignRole from './components/assign-role'
export default {
  name: 'Employees',
  components: {
    AddEmployee,
    AssignRole
  },
  data() {
    return {
      list: [],
      params: {
        page: 1, // 当前页
        size: 10 // 每页条数
      },
      total: 0, // 总数
      loading: false,
      showDialog: false,
      showCodeDialog: false,
      showRoleDialog: false,
      curId: null
    }
  },
  mounted() {
    this.getEmployeeList()
  },
  methods: {
    editRole(id) {
      this.showRoleDialog = true
      this.curId = id
      this.$refs.formRole.getRoleList()
    },
    assignDialog() {
      this.showRoleDialog = false
    },
    createQr(staffPhoto) {
      if (!staffPhoto) return // 有图片才显示弹层
      this.showCodeDialog = true
      this.$nextTick(() => {
        // 如果这里 url 写的是网址, 就会跳转到对应网址 (二维码分享效果)
        QrCode.toCanvas(this.$refs.myCanvas, staffPhoto)
      })
    },
    // 关闭弹框
    closeDialog() {
      this.showDialog = false
      this.getEmployeeList()
    },
    // 点击分页
    handleCurrentChange(page) {
      this.params.page = page
      this.getEmployeeList()
    },
    // 获取当前列表
    async getEmployeeList() {
      this.loading = true
      const data = await reqGetEmployeeList(this.params)
      const { total, rows } = data
      this.total = total
      this.list = rows
      this.loading = false
    },
    // 格式化聘用形式函数
    formatEmployment(type) {
      // 根据源数据经过处理 把处理之后的数据返回
      // 定义一个映射结构
      // {1::'正式', 0:'非正式'}
      const map = {
        1: '正式',
        2: '非正式'
      }
      return map[type]
    },
    // 处理时间函数
    formatDate(value, str = 'YYYY-MM-DD') {
      return dayjs(value).format(str)
    },
    async hDelEmployee(id) {
      this.$confirm('你确认要删除么?', '温馨提示')
        .then(async() => {
          this.list.length === 1 && this.params.page--
          await delEmployee(id)
          this.getEmployeeList()
          this.$message.success('删除员工成功')
        })
        .catch((error) => {
          this.$message.warning(error)
          console.log(error)
        })
    },
    // 导出功能
    exportEmployee() {
      import('@/vendor/Export2Excel').then(async excel => {
        // 1.准备表头中的中英文对应关系
        const headerRelation = {
          '手机号': 'mobile',
          '姓名': 'username',
          '入职日期': 'timeOfEntry',
          '工号': 'workNumber',
          '转正日期': 'correctionTime',
          '部门': 'departmentName'
        }
        // 2.调用接口准备表格数据 (从数组库拉取当前页的最新的数据完成导出)
        const res = await reqGetEmployeeList(this.params)
        // 3.调用处理方法进行数据处理
        const { data, header } = getExportData(res.rows, headerRelation)
        excel.export_json_to_excel({
          header: header, // 表头数据
          data: data, // 表格数据 (二维数组)
          filename: '员工列表',
          autoWidth: true,
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    }
  }
}
</script>
